<template>
  <view class="cart">

    <!-- 收货地址 -->
    <view class="cart_address">
      <view
        class="address_info"
        v-if="address"
      >
        <view class="address_name_wrap">
          <view>{{address.userName}}</view>
          <view>{{address.detail}}</view>
        </view>
        <view class="address_phone">{{address.telNumber}}</view>
      </view>
      <view
        class="cart_btn"
        v-else
      >
        <van-button
          color="#ff2d4a"
          type="primary"
          @click="getAddress"
        >收货地址</van-button>
      </view>
    </view>
    <!-- 购物车内容 -->
    <view class="cart_main">
      <view class="cart_title">购物车</view>
      <view class="cart_content">
        <view v-if="cartList.length">
          <van-swipe-cell
            async-close
            @close="onCartClose"
            :right-width="65"
            v-for="(item,index) in cartList"
            :key="index"
          >
            <view class="cart_item">
              <!-- !!!!! -->
              <view class="chk_wrap">
                <van-checkbox
                  @change="onChange(index)"
                  checked-color="#ff2d4a"
                  :value="item.checked"
                ></van-checkbox>
              </view>
              <view class="item_goods">
                <van-card
                  :price="item.goods_price"
                  :title="item.goods_name"
                  :thumb="item.goods_small_logo"
                  custom-class="custom-class"
                >
                  <view slot="footer">
                    <van-stepper
                      :value="item.count"
                      min="0"
                      @change="onCountChange(index,$event)"
                      async-change
                    />
                  </view>
                </van-card>
              </view>

              <!-- xxxxx -->
            </view>
            <view
              slot="right"
              class="cart_delete_wrap"
            >删除</view>
          </van-swipe-cell>
        </view>
        <view v-else>
          <image src="https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1602737951675&di=c0fe2f565a876e74191ae3f99890eb89&imgtype=0&src=http%3A%2F%2Fhbimg.b0.upaiyun.com%2Fe1b1467beea0a9c7d6a56b32bac6d7e5dcd914f7c3e6-YTwUd6_fw658" />

        </view>
      </view>
    </view>

    <!-- 提交订单 -->
    <van-submit-bar
      :price="countInfo.allPrice"
      :button-text="`结算(${countInfo.cateNums})`"
      @submit="onSubmit"
      :tip="true"
      custom-class="custom_class_btm"
    >

      <van-checkbox
        :value="countInfo.allChk"
        checked-color="#ff2d4a"
        @change="onAllChange"
      >全选</van-checkbox>

    </van-submit-bar>

  </view>
</template>

<script>
/* 
1 通过一个地址对象 来决定 按钮 切换显示
2 获取本地存储中的购物车的数据 数组 
3 点击复选框 change= 
  1 希望ui界面发生改变
     -> data中的数据 和 缓存中的数据都要发生改变 
4 通过 vue中的watch来实现即可 !! 
5 数量编辑功能
  1 通过 步进器  bind:change="onChange"
  2 当数量=1 同时用户点击 "-"  弹出窗口询问用户是否要删除 async-change
    否
    是 删除数据 
6 什么是
  张小龙 微信之父
 */

export default {
  data() {
    return {
      // 地址对象
      address: null,
      // 购物车数组
      cartList: [],
    };
  },
  watch: {
    // cartList(){
    //   console.log("cartList 被改变了");
    // },
    cartList: {
      // deep 深一层监控
      deep: true,
      // handler数据改变之后的模样
      handler(list) {
        // list 等一修改后的 cartList
        uni.setStorageSync("cartList", list);
      },
    },
  },
  computed: {
    countInfo() {
      // 1 是否全选 every
      let allChk =
        this.cartList.length !== 0 &&
        this.cartList.every((goods) => goods.checked);

      // 2 总价格
      let allPrice = 0;
      this.cartList.forEach((goods) => {
        // 已经勾选了的商品
        if (goods.checked) {
          allPrice += goods.count * goods.goods_price;
        }
      });
      return {
        // 是否全选
        // 总价格
        // 准备要结算的商品的种类 cateNums
        allChk,
        allPrice: allPrice * 100,
        cateNums: this.cartList.filter((goods) => goods.checked).length,
      };
    },
  },

  onShow() {
    this.cartList = uni.getStorageSync("cartList") || [];
  },

  methods: {
    // 获取收货地址
    async getAddress() {
      // 点击事件
      const res = await uni.chooseAddress();
      console.log(res);
      this.address = res[1];
      this.address.detail =
        this.address.provinceName +
        this.address.cityName +
        this.address.countyName +
        this.address.detailInfo;
    },
    // 商品的复选框选中
    onChange(index) {
      this.cartList[index].checked = !this.cartList[index].checked;
    },
    // 数量改变事件
    onCountChange(index, event) {
      console.log(event.detail);
      // this.cartList[index].count =event.detail;
      if (event.detail === 0) {
        this.deleteByIndex(index);
      } else {
        this.cartList[index].count = event.detail;
      }
    },
    // 点击 删除按钮
    async onCartClose(event) {
      const { instance } = event.detail;
      // 弹窗 询问用户 是否确定删除

      await this.deleteByIndex(0);
      console.log("准备关闭");
      // 等待用户点击了取消或者删除了 才关闭 滑动窗口
      instance.close();
    },
    // 根据索引来弹出创建删除数据
    // deleteByIndex 返回一个promise
    async deleteByIndex(index) {
      // [null,{}]
      const result = await uni.showModal({
        title: "提示",
        content: "您确定删除吗",
      });

      if (result[1].confirm) {
        // 要删除
        console.log("要删除");
        this.cartList.splice(index, 1);
        //  删除成功
        uni.showToast({
          title: "删除成功",
        });
      }
    },
    // 点击全选复选框
    onAllChange() {
      // 1 获取计算属性中 全选状态 = true
      // 2 对购物车数组做遍历即可
      // 3 获取到每一个商品对象 goods.checked=!全选状态
      const allChk = this.countInfo.allChk;
      this.cartList.forEach((goods) => {
        goods.checked = !allChk; // 如果一旦修改了数组的话  那么 allChk 不稳定
      });
    },

    // 点击结算
    onSubmit() {
      // 1 判断收货地址  有没有选中的商品
      if (!this.address || this.countInfo.cateNums === 0) {
        // 不合法

        uni.showToast({
          title: "请检查收货地址获取要购买的商品",
          icon: "none",
        });

        return;
      }

      // console.log("通过");

      // 传递参数 1 url 2 本地存储  3 全局应用对象 !!! getApp()

      const app = getApp();
      app.globalData.address = this.address;


      uni.navigateTo({url:"/pages/pay/pay"});
    },
  },
};
</script>

<style lang="less" >
.cart_address {
  .address_info {
    display: flex;
    justify-content: space-between;
    padding: 20rpx;
    border-bottom: 1rpx solid #eb4450;
  }
  .cart_btn {
    display: flex;
    justify-content: center;
    padding-top: 20rpx;
  }
}
.cart_main {
  .cart_title {
    padding: 20rpx;
    font-size: 32rpx;
    font-weight: 600;
    color: #eb4450;
    border-top: 1rpx solid #eb4450;
    border-bottom: 1rpx solid #eb4450;
  }
  .cart_content {
    .cart_item {
      border-bottom: 2rpx solid #ccc;

      display: flex;
      .chk_wrap {
        display: flex;
        align-items: center;
        padding: 0 30rpx;
      }
      .item_goods {
        flex: 1;
      }

      .custom-class {
        background-color: #fff !important;
      }
    }
    .cart_delete_wrap {
      background-color: #eb4450;
      color: #fff;
      width: 65px;
      height: 100%;
      font-size: 30rpx;
      display: flex;
      justify-content: center;
      align-items: center;
    }
  }
}

.custom_class_btm {
  border-top: 2rpx solid #ccc !important;
}
</style>